package com.cwd.arm.infrastructure.dao.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cwd.arm.infrastructure.dao.UserDao;
import com.cwd.arm.infrastructure.dao.base.DaoImpl;
import com.cwd.arm.infrastructure.mapper.UserMapper;
import com.cwd.arm.infrastructure.po.UserPo;
import com.cwd.arm.infrastructure.po.UserRolePo;
import com.cwd.arm.infrastructure.query.UserDaoQuery;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 * @author yan
 * @since 2021-11-08
 */
@Service
public class UserDaoImpl extends DaoImpl<UserMapper, UserPo> implements UserDao {

    @Override
    public UserPo getByUsername(String username) {
        QueryWrapper<UserPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName",username);
        return getOne(queryWrapper);
    }

    @Override
    public UserPo getByPhone(String phone) {
        QueryWrapper<UserPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        return getOne(queryWrapper);
    }

    @Override
    public UserPo getById(Long id) {
        return super.getById(id);
    }

    @Override
    public Page<UserPo> selectPage(UserDaoQuery daoQuery) {
        Page<UserPo> page=new Page<>(daoQuery.getCurrentPage(),daoQuery.getPageSize());
        QueryWrapper<UserPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("u.`id`= ur.`user_id`");
        queryWrapper.like(ObjectUtils.isNotEmpty(daoQuery.getRealName()),"u.real_name",daoQuery.getRealName());
        queryWrapper.like(ObjectUtils.isNotEmpty(daoQuery.getUsername()),"u.username",daoQuery.getUsername());
        queryWrapper.eq(ObjectUtils.isNotEmpty(daoQuery.getRoleId()),"ur.role_id",daoQuery.getRoleId());
        queryWrapper.eq(ObjectUtils.isNotEmpty(daoQuery.getEnabled()),"u.enabled",daoQuery.getEnabled());
        setSort(daoQuery, queryWrapper);
        page = baseMapper.selectPageWithRole(page,queryWrapper);
        setUserInfo(page.getRecords());
        return page;
    }

    @Override
    public List<UserPo> selectList(UserDaoQuery daoQuery) {
        QueryWrapper<UserPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjectUtils.isNotEmpty(daoQuery.getEnabled()),"enabled",daoQuery.getEnabled());
        return baseList(queryWrapper);
    }
}
